package oneplay.YonghongBITools.BatchDownload;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Getter
public class BatchDownloadConfig {

    public static String PATH = "path";
    public static String SHARE = "share";
    public static String PRINT = "print";
    public static String FIT_WIDTH = "fitWidth";
    public static String FIT_HEIGHT = "fitHeight";
    public static String LANDSCAPE = "landscape";
    public static String BATCH = "batch";

    private final String path;
    private final String name;
    private final Short fitWidth;
    private final Short fitHeight;
    private final boolean landscape;
    private final List<Map<String, String>> batchParams;

    public BatchDownloadConfig(File file) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(file);
        if (rootNode.hasNonNull(PATH) && rootNode.hasNonNull(BATCH)) {
            this.path = rootNode.get(PATH).asText();
            this.name = path.substring(path.lastIndexOf("/") + 1);
            if (rootNode.hasNonNull(PRINT)) {
                JsonNode printNode = rootNode.get(PRINT);
                fitWidth = printNode.hasNonNull(FIT_WIDTH) ? printNode.get(FIT_WIDTH).shortValue() : null;
                fitHeight = printNode.hasNonNull(FIT_HEIGHT) ? printNode.get(FIT_HEIGHT).shortValue() : null;
                landscape = printNode.hasNonNull(LANDSCAPE) && printNode.get(LANDSCAPE).booleanValue();
            } else {
                fitWidth = null;
                fitHeight = null;
                landscape = false;
            }
            this.batchParams = objectMapper.convertValue(rootNode.get(BATCH), new TypeReference<List<Map<String, String>>>() {
            });
            if (rootNode.hasNonNull(SHARE)) {
                Map<String, String> shareParams = objectMapper.convertValue(rootNode.get(SHARE), new TypeReference<Map<String, String>>() {
                });
                this.batchParams.forEach(item -> item.putAll(shareParams));
            }
        } else {
            log.error("Missing necessary field '{}' or '{}'", PATH, BATCH);
            throw new RuntimeException("JSON File Invalid");
        }
    }

}
